$(function () {

    // 时间范围
    $('#giftActivityPeriodValidity').daterangepicker({
        timePicker: true,
        startDate: moment().startOf('hour'),
        endDate: moment().startOf('hour').add(24, 'hour'),
        locale: {
            format: 'YYYY-MM-DD HH:mm',
            cancelLabel: '清空',
        },
        timePicker24Hour : true,
        autoUpdateInput: false,
    });
    $('#giftActivityPeriodValidity').on('apply.daterangepicker', function(ev, picker) {
        $(this).val(picker.startDate.format('YYYY-MM-DD HH:mm') + ' 至 ' + picker.endDate.format('YYYY-MM-DD HH:mm'));
    });
    $('#giftActivityPeriodValidity').on('cancel.daterangepicker', function(ev, picker) {
        $(this).val('');
    });

    // 初始化下拉菜单(赠品除外)
    $('form select:not("#giftList")').selectpicker({
        // liveSearch: false,
        sanitize: true,
        size: 10,
    });

    // 获取产品列表
    getProduct();
    // 初始化赠品类别状态
    giftCategoryStatus();

    // 赠品类别修改后，改变 关联产品、赠品和起止价格状态
    $('#giftCategory').on('changed.bs.select', function (e, clickedIndex, isSelected, previousValue) {
        giftCategoryStatus();
    });

    /**
     * 编辑页面相关功能
     * */

    if ($('#editGiftId').length) {
        getGiftInfo();
    }

});

// 赠品列表反显
function getGiftInfo() {
    var editGiftId = $('#editGiftId').val();
    $.ajax({
        url: "/customerGiftActivityRelation/selectGiftDropDownCheckedListByGiftActivityId?giftActivityId=" + editGiftId,
        type: "get",
        dataType: 'json',
        contentType: "application/x-www-form-urlencoded",
        success: function (data) {
            // console.log(data)
             var data = data.data;

            // 初始化选中项数组
            var giftArr = [];

            for (var i = 0; i < data.length; i++) {
                if (data[i].checked) {
                    giftArr.push(data[i].productId);
                }
            }
            // 反显选中条目
            $('#giftList').multiselect('select', giftArr);
        },
        error: function (err) {
            console.log(err);
        }
    })
}

// 赠品类别状态控制
function giftCategoryStatus() {
    var status = $('#giftCategory').val();

    var selectProduct = $('#productList');
    var giftActivityPrice = $('#giftActivityPrice');

    if (status == 1) {
        selectProduct.attr('disabled', false).selectpicker('refresh');
        giftActivityPrice.find('input').attr('disabled', true);
    } else if (status == 2) {
        selectProduct.attr('disabled', true).selectpicker('refresh');
        giftActivityPrice.find('input').attr('disabled', false);
    } else {
        selectProduct.attr('disabled', true).selectpicker('refresh');
        giftActivityPrice.find('input').attr('disabled', true);
    }
}

// 获取产品列表
function getProduct() {
    $.ajax({
        url: "/customerProduct/selectProductDropDownList",
        dataType: 'json',
        contentType: "application/x-www-form-urlencoded",
        success: function (data) {
            var data = data.data;

            var productListHtml = '';
            for (var i = 0; i < data.length; i++) {
                productListHtml += '<option tag-id="' + data[i].productCategories + '" value="' + data[i].productId + '">' + data[i].productName + '</option>'
            }

            $('#productList').html('<option value="1">全部产品</option>' + productListHtml).selectpicker('refresh');
            $('#giftList').html(productListHtml).multiselect("destroy").multiselect({
                filterPlaceholder: '搜索',
                enableFiltering: true,
                includeSelectAllOption: false,
                maxHeight: 300,
                selectAllText: '全部选择',
                nonSelectedText: '请选择',
                nSelectedText: '已选择',
                allSelectedText: '已选择全部',
                buttonWidth: '100%',
                buttonText: function(options, select) {
                    // console.log(options.length, select);

                    if (options.length === 0) {
                        return '请选择赠品';
                    } else {
                        return '已选择' + options.length + '个赠品';
                    }
                },
                onChange: function () {

                },
                onSelectAll: function () {
                    return '已选择全部'
                },
                onDeselectAll: function () {

                }
            });

            if ($('#editGiftId').length) {
                // 产品反显
                var editProductId = $('#editProductId').val();
                $('#productList').selectpicker('val', editProductId);
            }

        },
        error: function (err) {
            console.log(err);
        }
    })
}

/**
 * 添加赠品产品
 */
function addGiftProduct() {

    //赠品活动id
    var giftActivityId = $('#editGiftId').val();
    // 赠品活动名称
    var giftActivityName = $('#giftActivityName').val();
    // 起止时间
    var giftActivityPeriodValidity = $("#giftActivityPeriodValidity").val().split(' 至 ');
    // 起止时间-开始时间
    var giftPeriodValidityStart = giftActivityPeriodValidity[0];
    // 起止时间-结束时间
    var giftPeriodValidityEnd = giftActivityPeriodValidity[1];
    // 兑换方式
    var exchangeMethod = $("#exchangeMethod").val();
    // 赠品类别
    var giftCategory = $("#giftCategory").val();
    // 关联产品
    var productId = $('#productList').val();
    // 赠品
    var giftIdList = [];
    giftIdList = $('#giftList').val();
    // 起始价
    var giftActivityPriceStart = $.trim($("#giftActivityPriceStart").val());
    // 截止价
    var giftActivityPriceEnd =  $.trim($("#giftActivityPriceEnd").val());
    //关联产品会员类型
    var productCategories = $('#productList option:selected').attr("tag-id");

    //线索池名称为空和长度验证
    if (!giftActivityName) {
        promptInfo("赠品活动名称不能为空!");
        return;
    } else {
        if (giftActivityName.length > 20) {
            promptInfo("赠品活动名称长度不能大于20个字！");
            return;
        }
    }

    if (!giftActivityPeriodValidity) {
        promptInfo("起止时间必填！");
        return;
    }

    if (!exchangeMethod) {
        promptInfo("兑换方式必填！");
        return;
    }

    if (!giftIdList) {
        promptInfo("赠品必填！");
        return;
    }

    if (!giftCategory) {
        promptInfo("赠品类别必填！");
        return;
    }



    if(giftCategory==1){
        if (!productId) {
            promptInfo("关联产品必填！");
            return;
        }
        //起止价格清空
        giftActivityPriceStart = 0;
        giftActivityPriceEnd = 0;
    }else {
        if (!giftActivityPriceStart) {
            promptInfo("起始价必填！");
            return;
        }

        if (!giftActivityPriceEnd) {
            promptInfo("截止价必填！");
            return;
        }

        if (parseInt(giftActivityPriceStart)>parseInt(giftActivityPriceEnd)) {
            promptInfo("起始价必须小于等于截止价！");
            return;
        }
        //关系产品清空
        productId = '';
    }


    var jsonData = {
        "productGiftActivityId":giftActivityId,
        "giftActivityName":giftActivityName,
        "giftPeriodValidityStart":giftPeriodValidityStart,
        "giftPeriodValidityEnd":giftPeriodValidityEnd,
        "exchangeMethod":exchangeMethod,
        "giftCategory":giftCategory,
        "customerProductId":productId,
        "productCategories":productCategories,
        "exchangeMethod":exchangeMethod,
        "giftIdList":giftIdList,
        "giftActivityPriceStart":giftActivityPriceStart,
        "giftActivityPriceEnd":giftActivityPriceEnd
    };

    $.ajax({
        url: '/customerProductGiftActivity/addProductGiftActivity',
        type: 'POST',
        dataType: "json",
        contentType: "application/json;charset=utf-8",
        data: JSON.stringify(jsonData),
        success: (function (data) {
            if(data.code == '000000'){
                $.alert({
                    title: '提示',
                    content: '保存成功！',
                    buttons: {
                        confirm: {
                            text: '确认',
                            btnClass: 'btn-primary',
                            action: function () {
                                var $thisTabs = parent.$('.mt-nav-bar .nav-tabs').find('li.active');
                                var navTab = parent.$multitabs._getNavTab($thisTabs);
                                closeTab(navTab);
                                openTab("赠品列表", "/front/activityManager/productGiftForm");

                                // 提交完表单，重新加载相关table列表页面
                                refreshActivePane('/front/activityManager/productGiftForm');
                                delStorageAndRemove(navTab);
                            }
                        }
                    }
                });
            } else if(data.code == 'PG0001'){
                //活动名称重复
                $.alert(data.message);
            }else {
                $.alert("保存失败");
            }
        }),
        error: (function (res) {
            $.alert("保存失败");
        })
    })

}

/**
 * 取消新郑赠品活动
 */
function cancelAddGiftProduct(){
    $('form')[0].reset();
    $('form').find('select').selectpicker('refresh');
}

function promptInfo(content) {
    $.alert({
        title: '温馨提示',
        content: content,
        buttons: {
            confirm: {
                text: '确认',
                btnClass: 'btn-primary'
            }
        }
    });
}